// pages/room-detail/room-detail.js
const app = getApp();

Page({
  data: {
    roomId: '',
    roomCode: '',
    roomInfo: {
      name: '',
      code: '',
      game_type: 'mahjong',
      max_players: 4,
      status: 'waiting'
    },
    players: [],
    recentTransactions: [],
    roomStatusText: '等待中',
    gameTypeText: '麻将',
    roomQRCode: '',
    isCreator: false,
    
    // 弹窗控制
    showQRCodeModal: false,
    showTransactionModal: false,
    
    // 记账表单
    transactionType: 'debit', // debit: 我欠, credit: 欠我
    selectedPlayerIndex: 0,
    playerNames: [],
    transactionAmount: '',
    transactionRemark: ''
  },
  
  onLoad: function(options) {
    this.setData({
      roomId: options.id,
      roomCode: options.code || ''
    });
    
    // 加载房间信息
    this.loadRoomInfo();
  },
  
  onShow: function() {
    // 每次显示页面时刷新数据
    if (this.data.roomId) {
      this.loadRoomInfo();
    }
  },
  
  // 加载房间信息
  loadRoomInfo: function() {
    const that = this;
    
    wx.showLoading({ title: '加载中...' });
    
    // 获取房间详情
    app.request(`/room/${this.data.roomId}`).then(roomRes => {
      // 更新房间信息
      that.setData({
        roomInfo: roomRes.room,
        players: roomRes.players,
        roomStatusText: that.getRoomStatusText(roomRes.room.status),
        gameTypeText: that.getGameTypeText(roomRes.room.game_type),
        isCreator: roomRes.room.creator_id === app.globalData.userInfo.id
      });
      
      // 准备玩家选择器数据
      const playerNames = roomRes.players
        .filter(p => p.id !== app.globalData.userInfo.id)
        .map(p => ({ id: p.id, nickname: p.nickname }));
      
      that.setData({ 
        playerNames: playerNames,
        selectedPlayerIndex: 0
      });
      
      // 获取房间二维码
      that.generateRoomQRCode();
      
      // 获取交易记录
      return app.request(`/transaction/room/${that.data.roomId}`, {
        params: { limit: 5 }
      });
    }).then(transactionRes => {
      wx.hideLoading();
      
      // 格式化交易记录
      const transactions = transactionRes.map(t => ({
        id: t.id,
        description: t.description || `与${t.other_user_name}的交易`,
        amount: t.amount,
        time: that.formatTime(t.created_at)
      }));
      
      that.setData({ 
        recentTransactions: transactions
      });
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    });
  },
  
  // 获取房间状态文本
  getRoomStatusText: function(status) {
    const statusMap = {
      waiting: '等待中',
      playing: '游戏中',
      closed: '已关闭'
    };
    return statusMap[status] || '未知';
  },
  
  // 获取游戏类型文本
  getGameTypeText: function(type) {
    const typeMap = {
      mahjong: '麻将',
      poker: '扑克',
      doudizhu: '斗地主',
      other: '其他'
    };
    return typeMap[type] || '未知';
  },
  
  // 格式化时间
  formatTime: function(time) {
    const date = new Date(time);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },
  
  // 生成房间二维码
  generateRoomQRCode: function() {
    const qrCodeContent = `room://${this.data.roomInfo.code}`;
    // 这里应该调用生成二维码的接口，暂时使用一个占位图
    this.setData({
      roomQRCode: 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(qrCodeContent)
    });
  },
  
  // 分享房间
  shareRoom: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  
  // 复制房间号
  copyRoomCode: function() {
    wx.setClipboardData({
      data: this.data.roomInfo.code,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
      }
    });
  },
  
  // 显示二维码弹窗
  showQRCode: function() {
    this.setData({ showQRCodeModal: true });
  },
  
  // 隐藏二维码弹窗
  hideQRCodeModal: function() {
    this.setData({ showQRCodeModal: false });
  },
  
  // 显示记账弹窗
  showTransactionModal: function() {
    if (this.data.players.length < 2) {
      wx.showToast({
        title: '至少需要两名玩家才能记账',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ 
      showTransactionModal: true,
      transactionAmount: '',
      transactionRemark: ''
    });
  },
  
  // 隐藏记账弹窗
  hideTransactionModal: function() {
    this.setData({ showTransactionModal: false });
  },
  
  // 切换交易类型
  onTransactionTypeChange: function(e) {
    this.setData({
      transactionType: e.detail.value ? 'credit' : 'debit'
    });
  },
  
  // 选择玩家
  onPlayerChange: function(e) {
    this.setData({
      selectedPlayerIndex: e.detail.value
    });
  },
  
  // 输入金额
  onAmountInput: function(e) {
    this.setData({
      transactionAmount: e.detail.value
    });
  },
  
  // 输入备注
  onRemarkInput: function(e) {
    this.setData({
      transactionRemark: e.detail.value
    });
  },
  
  // 提交交易
  submitTransaction: function() {
    // 验证输入
    if (!this.data.transactionAmount || parseFloat(this.data.transactionAmount) <= 0) {
      wx.showToast({
        title: '请输入有效的金额',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.playerNames[this.data.selectedPlayerIndex]) {
      wx.showToast({
        title: '请选择交易玩家',
        icon: 'none'
      });
      return;
    }
    
    const amount = parseFloat(this.data.transactionAmount);
    const toUserId = this.data.playerNames[this.data.selectedPlayerIndex].id;
    const fromUserId = this.data.transactionType === 'debit' ? 
      app.globalData.userInfo.id : toUserId;
    const actualToUserId = this.data.transactionType === 'debit' ? 
      toUserId : app.globalData.userInfo.id;
    
    wx.showLoading({ title: '记账中...' });
    
    app.request('/transaction/add', {
      method: 'POST',
      data: {
        room_id: this.data.roomId,
        from_user_id: fromUserId,
        to_user_id: actualToUserId,
        amount: amount,
        remark: this.data.transactionRemark
      }
    }).then(() => {
      wx.hideLoading();
      
      wx.showToast({
        title: '记账成功',
        icon: 'success'
      });
      
      // 关闭弹窗并刷新数据
      this.hideTransactionModal();
      this.loadRoomInfo();
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message || '记账失败',
        icon: 'none'
      });
    });
  },
  
  // 查看所有交易记录
  viewAllTransactions: function() {
    wx.navigateTo({
      url: `/pages/transactions/transactions?room_id=${this.data.roomId}`
    });
  },
  
  // 开始游戏
  startGame: function() {
    if (this.data.players.length < 2) {
      wx.showToast({
        title: '至少需要两名玩家才能开始游戏',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({ title: '开始游戏中...' });
    
    app.request(`/room/${this.data.roomId}/start`, {
      method: 'POST'
    }).then(() => {
      wx.hideLoading();
      
      wx.showToast({
        title: '游戏开始',
        icon: 'success'
      });
      
      // 刷新房间信息
      this.loadRoomInfo();
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message || '操作失败',
        icon: 'none'
      });
    });
  },
  
  // 关闭房间
  closeRoom: function() {
    wx.showModal({
      title: '确认关闭',
      content: '确定要关闭这个房间吗？',
      success: res => {
        if (res.confirm) {
          wx.showLoading({ title: '关闭中...' });
          
          app.request(`/room/${this.data.roomId}/close`, {
            method: 'POST'
          }).then(() => {
            wx.hideLoading();
            
            wx.showToast({
              title: '房间已关闭',
              icon: 'success'
            });
            
            // 返回首页
            setTimeout(() => {
              wx.switchTab({ url: '/pages/index/index' });
            }, 1500);
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: err.message || '操作失败',
              icon: 'none'
            });
          });
        }
      }
    });
  },
  
  // 页面分享
  onShareAppMessage: function() {
    return {
      title: `${app.globalData.userInfo.nickname}邀请你加入房间：${this.data.roomInfo.name}`,
      path: `/pages/room-detail/room-detail?code=${this.data.roomInfo.code}`,
      imageUrl: ''
    };
  }
});